﻿using System;
using System.Collections.Generic;
using System.Text;
using FeedDotNet.Common;
using FeedDotNet;
using System.Globalization;

namespace ConsoleApplication
{
    internal class RSSMerger
    {
        public static Feed FetchFeed(List<IFeedProvider> feedProviders)
        {
            FeedFetcher ff = new FeedFetcher(feedProviders);
            ff.FetchFeeds();

            List<Feed> feeds = new List<Feed>();
            foreach (IFeedProvider provider in feedProviders)
            {
                if (provider.FullFeed != null)
                    feeds.Add(provider.FullFeed);
                else
                    Console.WriteLine("Feed Fetch Failed: " + provider.Key);
            }

            Console.WriteLine();
            Feed merged = collapseFeeds(feeds);
            return merged;
        }

        public static List<MovieFeedItem> FetchNewFeed(List<IFeedProvider> feedProviders)
        {
            FeedFetcher ff = new FeedFetcher(feedProviders);
            ff.FetchFeeds();

            List<MovieFeedItem> feedItems = new List<MovieFeedItem>();
            foreach (IFeedProvider provider in feedProviders)
            {
                
                MovieFeed movieFeed = provider as MovieFeed;
                if (movieFeed != null && movieFeed.FullFeed != null)
                {
                    foreach (MovieFeedItem fi in movieFeed.GetNewFeedItems())
                        feedItems.Add(fi);
                }
                else
                    Console.WriteLine("Feed Fetch Failed: " + provider.Key);
            }

            feedItems = MovieFeedItem.Distinct(feedItems);

            return feedItems;
        }

        private static Feed collapseFeeds(List<Feed> feeds)
        {
            Feed resultantFeed = new Feed();
            List<FeedItem> feedItems = new List<FeedItem>();
            setupResultFeed(resultantFeed);

            foreach (Feed movieList in feeds)
            {
                feedItems.AddRange(movieList.Items);
            }

            feedItems = MovieFeedItem.Distinct(feedItems);
            feedItems.Sort(MovieFeedItem.DateComparer);

            resultantFeed.Items = feedItems;

            return resultantFeed;
        }

        private static void setupResultFeed(Feed resultantFeed)
        {
            resultantFeed.Description = "List of newest movies released on UseNet";
            resultantFeed.Language = "googlaruean";
            resultantFeed.Title = "UseNet's Newest Awesome";
        }
    }
}
